package pers.dawnyang.config.mybatis;

import java.util.Date;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import pers.dawnyang.modular.system.domain.common.UserInfo;

/**
 * MP数据表公共字段自动填充
 * 
 * @author dawn yang
 * @date 2020/12/16
 */
@Component
@Slf4j
public class MetaHandler implements MetaObjectHandler {

  /**
   * 新增数据执行
   * 
   * @param metaObject
   */
  @Override
  public void insertFill(MetaObject metaObject) {
    String userName = "sys";
    try {
      Subject subject = SecurityUtils.getSubject();
      UserInfo user = (UserInfo) subject.getPrincipal();
      if (null != user) {
        userName = user.getUserName();
      }
    } catch (Exception e) {
    }
    this.setFieldValByName("createTime", new Date(), metaObject);
    this.setFieldValByName("createUser", userName, metaObject);
  }

  /**
   * 更新数据执行
   * 
   * @param metaObject
   */
  @Override
  public void updateFill(MetaObject metaObject) {
    String userName = "sys";
    Subject subject;
    try {
      subject = SecurityUtils.getSubject();
      UserInfo user = (UserInfo) subject.getPrincipal();
      if (null != subject.getPrincipal()) {
        userName = user.getUserName();
      }
    } catch (Exception e) {
    }
    this.setFieldValByName("updateTime", new Date(), metaObject);
    this.setFieldValByName("updateUser", userName, metaObject);
  }

}
